<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

class DingTalkApp extends BaseModel
{
    use HasFactory;
    protected $table = 'dingtalk_app';
    protected $guarded = [];

    public static function saveitems($items = [])
    {
        $user_id = user()->id;
        $role_ids = self::where("creator_id", $user_id)->pluck('id', 'id')->toArray();
        foreach ($items as $v) {
            if (isset($v['id']) && (int)$v['id'] > 0) {
                if (isset($role_ids[$v['id']])) {
                    self::where("id", $v['id'])->update($v);
                    unset($role_ids[$v['id']]);
                } else
                    throwError("保存配置时错误！");
            } else {
                self::create(array_filter($v));
            }
        }
        //删除已经不存在的
        foreach (self::whereIn("id", $role_ids)->get() as $v) {
            $v->delete();
        };
    }

    public function appUrl()
    {
        return $this->hasMany(DingTalkAppUrl::class, 'app_id');
    }
    public function _deleting($model)
    {
        // $url = ->get();
        $model->appUrl->filter(function ($value, $key) {
            $value->delete();
        });
    }
    public function _creating(&$model)
    {
        $model['creator_id'] = user()->id;
    }
    public function _created($model)
    {
        if ($model->kind != '机器人') {
            DingTalkAppUrl::create(['name' => '订阅请求网址', 'app_id' => $model->id, 'url' => "/DingTalkInterface/server/{$model->name}"]);
            DingTalkAppUrl::create(['name' => '免登授权码跳转地址', 'app_id' => $model->id, 'url' => "/DingTalkInterface/oauth/{$model->name}"]);
            DingTalkAppUrl::create(['name' => '扫码授权码跳转地址', 'app_id' => $model->id, 'url' => "/DingTalkInterface/oauthqrcode/{$model->name}"]);
        } else {
            DingTalkAppUrl::create(['name' => '钉钉机器人接受消息地址', 'app_id' => $model->id, 'url' => "/DingTalkInterface/robot/{$model->name}"]);
        }
    }
}
